package com.example.demo.modules.es.service.impl;

import com.example.demo.modules.es.entity.User;
import com.example.demo.modules.es.service.UserService;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class UserServiceImpl implements UserService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public String createIndex(String indexName) {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
        if(indexOperations.exists()){
            return indexName + "索引已存在！";
        }else{
            boolean create = indexOperations.create();
            return create ? "创建" + indexName + "索引成功" : "创建" + indexName + "失败";
        }
    }

    @Override
    public String deleteIndex(String indexName) {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
        if(indexOperations.exists()){
            boolean delete = indexOperations.delete();
            return delete ? "删除" + indexName + "索引成功" : "删除" + indexName + "失败";
        }else{
            return indexName + "索引不存在";
        }
    }

    @Override
    public String save(User user) {
        elasticsearchRestTemplate.save(user);
        return "成功";
    }

    @Override
    public String delete(String id) {
        elasticsearchRestTemplate.delete(id, User.class);
        return "成功";
    }
}
